package com.huiyou.adminapi.service;

import com.huiyou.adminapi.common.model.Product;
import com.huiyou.adminapi.repository.ProductRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Service
@Slf4j
public class ProductService {


    private final ProductRepository productRepository;

    @Autowired
    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public Page<Product> findAll(String name, Pageable pageable) {
        return productRepository.findByNameContainingOrderByUpdateTimeDesc(name, pageable);
    }

    public Product findById(String id) {
        return productRepository.findById(id).orElse(null);
    }

    public void save(Product product) {
        List<Product> productList = null;
        if (product.getId() == null) {
            product.setCreatorTime(System.currentTimeMillis());
            productList = productRepository.findByName(product.getName());

        } else {
            product.setUpdateTime(System.currentTimeMillis());
            productList = productRepository.findByNameAndIdIsNot(product.getName(), product.getId());
        }
        if(productList.size() > 0){
            throw new RuntimeException("产品名称已存在!");
        }
        productRepository.save(product);
    }

    public void deleteById(String id) {
        productRepository.deleteById(id);
    }

}
